package com.example.musicplayer.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.example.musicplayer.DataLoadManager;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.user.UserManage;

public class InitialService extends Service {
    //记录是否第一次启动
    private static boolean sFirstStart = true;
    private static SuccessCallBack sCallBack;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (sFirstStart) {
            readMusicInfo(intent);
            //read login state
            DataLoadManager.readLoginState();
            boolean userLogin = UserManage.getUserLogin();
            if (userLogin) {
                MusicInfo.initUserMusicInfo();
            }
            //初始化结束，停止服务线程
            sFirstStart = false;
            if (sCallBack != null) {
                sCallBack.done(!userLogin);
            }
        }
        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }

    //读取本地音乐信息
    private void readMusicInfo(Intent intent) {
        int authority = intent.getIntExtra("authority", -1);
        if (authority == 0) {
            MusicInfo.initMusicInfo();
        }
    }

    public static void setCallBack(SuccessCallBack callBack) {
        sCallBack = callBack;
    }

    //服务启动完成回调接口
    public interface SuccessCallBack {
        void done(boolean needLogin);
    }
}